package com.centaline.androidsalesblog.rx.request;

import com.android.volley.VolleyError;
import com.centaline.androidsalesblog.api.sale.StaffApi;
import com.centaline.androidsalesblog.model.databaseobject.StaffDo;
import com.centaline.androidsalesblog.model.responseobject.StaffRo;
import com.centanet.framework.interfaces.IResponseListener;

import rx.Observable;
import rx.Subscriber;

/**
 * 融云用户信息
 * Created by guilin on 16/3/18.
 */
final class RequestStaffOnSubscribe implements Observable.OnSubscribe<StaffDo> {

    private final Class<?> tag;
    private final String targetId;

    public RequestStaffOnSubscribe(Class<?> tag, String targetId) {
        this.tag = tag;
        this.targetId = targetId;
    }

    @Override
    public void call(final Subscriber<? super StaffDo> subscriber) {
        if (targetId != null &&
                targetId.startsWith("s")) {
            final String[] split = targetId.split("_");
            if (split.length == 3) {
                StaffApi staffApi = new StaffApi(tag, StaffRo.class, new IResponseListener<StaffRo>() {
                    @Override
                    public void onResponse(StaffRo staffRo) {
                        if (staffRo != null &&
                                !subscriber.isUnsubscribed()) {
                            StaffDo staffDo = staffRo.getStaffDo();
                            subscriber.onNext(staffDo);
                        }
                        subscriber.onCompleted();
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        subscriber.onError(error);
                    }
                });
                staffApi.setStaffNo(split[2]);
                staffApi.startRequest();
            }
        } else {
            subscriber.onCompleted();
        }
    }
}
